$(document).ready(function(){
	$("#btnFilter").click(function(){
		filterSemesterBySelectedOption();
	});
	$("#bthAdd").click(function(){
		popupAddDialog();
	});

	filterSemesterBySelectedOption();
	
	initDialog();
});

function filterSemesterBySelectedOption() {
	filterSemester($("#selectActive").val());
}

function initDialog() {
	// 初始化弹出表单中的学年可选项
    $.ajax({
        type: "GET",
        url: "../public/school-years",
        dataType: "json",
        success: function (resp) {
            if (resp.code == "0") {
                var schoolYearSelectObj = $("#semesterDialog #schoolYear");
                $.each(resp.data,function(index, item) {
                	var optionHtml = "<option value='" + item.code + "'>" + item.name + "</option>";
                	schoolYearSelectObj.append(optionHtml);
                });
            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

function filterSemester(active) {
	$("#txtMessage").text("页面正在加载...")
	var url = location.href + "/..";
    $.ajax({
        type: "GET",
        url: url,
        data: {active: active},
        dataType: "json",
        success: function (resp) {
            if (resp.code == "0") {
                var tableBodyObj = $("#tableSemesters tbody");
                tableBodyObj.html("");
                $.each(resp.data,function(index, item) {
                	var rowHtml = "<tr dataStr=" + JSON.stringify(item) + ">";
                	rowHtml += "<td>" + item.id + "</td>";
                	rowHtml += "<td>" + item.name + "</td>";
                	rowHtml += "<td>" + item.schoolYearName + "</td>";
                	rowHtml += "<td>" + item.active + "</td>";
                	rowHtml += "<td><span class='clickable' onclick='popupEditDialog(event)'>edit</span></td>";
                	rowHtml += "</tr>";
                	tableBodyObj.append(rowHtml);
                });
                
                var countSummaryObj = $("#txtCountSummary");
                countSummaryObj.html("共 " + resp.data.length + " 条记录");
                
            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        	$("#txtMessage").text("");
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

var semesterDialog = $("#semesterDialog").dialog({
    autoOpen: false,
    height:250,
    width: 300,
    modal: true,
	close: function() {}
});

function popupAddDialog() {
    $("#semesterDialog #id").val("");
    $("#semesterDialog #name").val("");
    $("#semesterDialog input[name='active'][value='true']").checked = true;
    
	semesterDialog = semesterDialog.dialog({
		label: "增加新的学期",
	    buttons: {
	    	"添加新学期": addSemester,
	    	Cancel: function() {
	    		semesterDialog.dialog("close");
	    	}
	    }
	});
	semesterDialog.dialog("open");
}

function addSemester() {
	var name = $("#semesterDialog #name").val();
	var schoolYearId =  $("#semesterDialog #schoolYear").val();
	var active = $("#semesterDialog input[name='active']:checked").val();
	var postData = {name:name, schoolYearId:schoolYearId, active:active};
	var url = location.href + "/..";
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	semesterDialog.dialog("close");
            	filterSemester(); // 刷新页面
                
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });    
}

function popupEditDialog(event) {
	event = event || window.event;
    var sourceObj = event.srcElement || event.target;
    var trObject = $(sourceObj).closest("tr");
    var item = JSON.parse(trObject.attr("dataStr"));
    
    $("#semesterDialog #id").val(item.id);
    $("#semesterDialog #name").val(item.name);
    var radioSelectorStr = "#semesterDialog input[name='active'][value='" + item.active + "']";
    $(radioSelectorStr).get(0).checked = true;
    $("#semesterDialog #schoolYear").val(item.schoolYearId);
    
	semesterDialog = semesterDialog.dialog({
		label: "修改学期设置",
	    buttons: {
	    	"保存修改内容": updateSemester,
	    	Cancel: function() {
	    		semesterDialog.dialog("close");
	    	}
	    }
	});
	semesterDialog.dialog("open");

    
}

function updateSemester() {
	var id = $("#semesterDialog #id").val();
	var name = $("#semesterDialog #name").val();
	var schoolYearId =  $("#semesterDialog #schoolYear").val();
	var active = $("#semesterDialog input[name='active']:checked").val();
	var postData = {id:id, name:name, schoolYearId:schoolYearId, active:active};
    $.ajax({
        type: "POST",
        url: id,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	semesterDialog.dialog("close");
            	filterSemester(); // 刷新页面               
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}
